package com.javajun.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javajun.custom.JqGridParm;
import com.javajun.custom.JqGridUtils;
import com.javajun.entity.Customer;
import com.javajun.entity.Enterprise;
import com.javajun.entity.Invoice;
import com.javajun.form.JInvoiceForm;
import com.javajun.service.CustomerService;
import com.javajun.service.InvoiceService;

@Controller
@RequestMapping(value="/customerInvoice")
public class CustomerInvoiceController {
    
    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value="/manage")
    public String manage(ModelMap map) {
        return "customerInvoice/manage";
    }
    
    @RequestMapping(value = "/getlist", method = RequestMethod.POST)
    // 返回json数据
    @ResponseBody
    public Object getList(JqGridParm parm) {
        Pageable pageable = parm.buildPageable();
        Enterprise enterprise = findByUsername();
        Page<Invoice> page = null;
        if (!parm.getSearch()) {
            // page = customerService.findByEnterprise(enterprise, pageable);
            page = invoiceService.findByEnterprise(enterprise, pageable);
        } else {
            // page = enterpriseService.findAll(parm.buildSpec(), pageable);
        }
        HashMap<String, Object> pageResult = JqGridUtils.getPageResult(page);
        return pageResult;
    }
    
    @RequestMapping(value = { "/add", "/edit" }, method = RequestMethod.POST)
    @ResponseBody
    public Object addAndEdit(ModelMap map, String[] id, JInvoiceForm form) {
        String mess = "";
        if (form.getOper().equals("add")) {
            Integer invoiceId = null;
            save(invoiceId, form);
            mess = "Add is OK!";
        } else if (form.getOper().equals("edit")) {
            Integer invocieId = null;
            for (int i = 0; i < id.length; i++) {
                System.out.println(id[i]);
                invocieId = Integer.parseInt(id[i]);
            }
            save(invocieId, form);
            // save(enterpriseId, form);
        } else if (form.getOper().equals("del")) {
            for (int i = 0; i < id.length; i++) {
                delete(map, Integer.parseInt(id[i]));
                System.out.println("删除用户id：" + id[i]);
            }
            mess = "Delete is OK!";
            System.out.println(mess);
        }
        return mess;
    }

    
    private void save(Integer id, JInvoiceForm form) {

        // 时间格式化格式
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");

        Invoice entity = new Invoice();
        if (id != null) {
            entity = invoiceService.findById(id);
        }

        // 1.发票代码
        // 2.发票号码
        // 3.开票日期
        // 4.开票金额
        // 5.申请报销日期
        // 6.报销人

        if (StringUtils.hasText(form.getInvoiceCode())) {
            entity.setInvoiceCode(form.getInvoiceCode());
        }

        if (StringUtils.hasText(form.getInvoiceNum())) {
            entity.setInvoiceNum(form.getInvoiceNum());
        }

        if (StringUtils.hasText(form.getInvoiceDateStr())) {
            Date time = new Date();
            try {
                time = timeFormat.parse(form.getInvoiceDateStr());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            entity.setInvoiceDate(time);
        }

        if (form.getInvoiceMoney() != null) {
            entity.setInvoiceMoney(form.getInvoiceMoney());
        }

        if (StringUtils.hasText(form.getApplyDateStr())) {
            Date time = new Date();
            try {
                time = timeFormat.parse(form.getApplyDateStr());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            entity.setApplyDate(time);
        }

        // 报销人
        if (StringUtils.hasText(form.getWhoExpenses())) {
            entity.setWhoExpenses(form.getWhoExpenses());
        }
        
        // 发票所属租户
        if(entity.getEnterprise() == null) {
            Enterprise enterprise = new Enterprise();
            entity.setEnterprise(enterprise);
        }
        entity.setEnterprise(findByUsername());
        
        // 保存
        invoiceService.save(entity);
    }

    /**
     * Delete 通过Id删除一条发票
     * @param map
     * @param id
     */
    private void delete(ModelMap map, Integer id) {
        if (id != null) {
            invoiceService.deleteById(id);
        }
    }
    
    /**
     * Get 获取当前登录的用户的所属租户
     * @return
     */
    public Enterprise findByUsername() {
        String currentUsername = customerService.getCurrentUsername();
        Customer cusomer = customerService.findByUsername(currentUsername);
        return cusomer.getEnterprise();
    }
    
    @RequestMapping(value="/check")
    @ResponseBody
    public String check(String invoiceCode, String invoiceNum) {
        
        if (StringUtils.hasText(invoiceCode)) {
            Invoice invoice = invoiceService.findByInvoiceCode(invoiceCode);
            if (invoice != null) {
                return "codein";
            }
        }
        if (StringUtils.hasText(invoiceNum)) {
            Invoice invocie = invoiceService.findByInvoiceNum(invoiceNum);
            if (invocie != null) {
                return "numin";
            }
        }
        return "ok";
    }
}
